<script setup lang="ts">
import { getAttributeListAPI } from '@/api/product/attribute'
import { getSpuDetailAPI } from '@/api/product/spu'
import type { AttributeItem } from '@/types/product/attribute'
import { ref } from 'vue'
import type { SPUImageItem , SPUSaleAttrItem} from '@/types/product/spu'
import type { AddSkuParams,SkuImageItem } from '@/types/product/sku'
import { addSkuAPI } from '@/api/product/sku'
import { ElMessage} from 'element-plus'

// 父组件触发事件
const emit  = defineEmits(['cancel'])

// 取消逻辑
const handleCancel = () => {
    // 清空表单数据
    formData.value = {
    skuDesc: '',
    price: 0,
    category3Id: '',
    skuAttrValueList: [],
    skuDefaultImg: '',
    skuImageList: [],
    skuSaleAttrValueList: [],
    weight: 0,
    spuId: '',
    skuName: '',
    tmId: ''
    }
    // 平台属性数据
    attributeList.value = []
    // 销售属性数据
    saleAttrList.value = []
    // 商品图片数据
    skuImageList.value = []
    emit('cancel')
}

// 表单数据
 const formData = ref<AddSkuParams>({
    skuDesc: '',
    price: 0,
    category3Id: '',
    skuAttrValueList: [],
    skuDefaultImg: '',
    skuImageList: [],
    skuSaleAttrValueList: [],
    weight: 0,
    spuId: '',
    skuName: '',
    tmId: ''
})

// 平台属性数据
const attributeList = ref<AttributeItem[]>([])

// 获取平台属性
const getAttributeList = async (categoryParmas: any) => {
   const res = await getAttributeListAPI(categoryParmas.category1Id,categoryParmas.category2Id,categoryParmas.category3Id)
   attributeList.value = res.data
//    console.log(attributeList.value);
   // 初始化平台属性数据
    // 通过获取的spu平台数据为sku平台数据添加属性id,但属性值ID滞空，等待用户选择
   const AttrValueList = attributeList.value.map((item: AttributeItem ) => {
        return {
            attrId: item.id as number,
            valueId: ''
        }
   })
   formData.value.skuAttrValueList = AttrValueList
}

// 销售属性数据
const saleAttrList = ref<SPUSaleAttrItem[]>([])

// 商品图片数据
const skuImageList = ref<SPUImageItem[]>([])

// 获取spu数据信息
const  getSpuInfo = async  (spuId: number | string) => {
    const res = await getSpuDetailAPI(spuId)
    saleAttrList.value = res.data.spuSaleAttrList
    skuImageList.value = res.data.spuImageList
    // 初始化销售属性数据
    const SaleAttrValueList = saleAttrList.value.map((item: SPUSaleAttrItem) => {
        return {
            saleAttrId: item.id as number,
            saleAttrValueId: ''
        }
    })
    formData.value.skuSaleAttrValueList = SaleAttrValueList
    // 初始化图片数据
    const imgList = skuImageList.value.map((item: SPUImageItem) => {
        return {
            imgName: item.imgName,
            imgUrl: item.imgUrl,
            isDefault: 0,
            spuImgId: item.id
        }
    })
    formData.value.skuImageList = imgList
}

// 获取sku数据
const getSkuData = (categoryParmas: any,spuId: number | string,tmId: string | number) => {
     getAttributeList(categoryParmas)
     getSpuInfo(spuId)
     formData.value.category3Id = categoryParmas.category3Id
     formData.value.spuId = spuId
     formData.value.tmId = tmId
}

// 对外暴露使父组件调用
defineExpose({
    getSkuData
})

// 图片表格对象
const tableImgRef = ref()

// 选择默认图片
const handelDefaultImg = (row: SkuImageItem) => {
    // 取消之前默认图片的选中状态
    formData.value.skuImageList.forEach((item: SkuImageItem) => {
        item.isDefault = 0
    })
    // 清空表格的选中状态
    tableImgRef.value.clearSelection()
    tableImgRef.value.toggleRowSelection(row,true)
    row.isDefault = 1
}

// 保存SKU
const addSku = async () => {
    // 收集数据
    formData.value.skuDefaultImg = formData.value.skuImageList.find((item: SkuImageItem) => item.isDefault === 1)?.imgUrl || ''
    console.log(formData.value);
    
    if(formData.value.skuDefaultImg === '') {
        return ElMessage.warning('请选择默认图片')
    }
    // 发送请求
    const res = await addSkuAPI(formData.value)
    if(res.code === 200) {
        // 提示用户
        ElMessage.success('添加SKU成功')
        // 取消
        handleCancel()
    }
}

// 主干数据校验表单
const formRules = {
    skuName: [
        { required: true, message: '请输入sku名称', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
    ],
    weight: [
        { required: true, message: '请输入重量', trigger: 'blur' }
    ],
    skuDesc: [
        { required: true, message: '请输入sku描述', trigger: 'blur' }
    ]
}

// 平台属性表单校验
const attributeFormRules = {
    valueId: [
        { required: true, message: '请选择属性值', trigger: 'change' }
    ]
}

// 销售属性表单校验
const saleAttrFormRules = {
    saleAttrValueId: [
        { required: true, message: '请选择销售属性', trigger: 'change' }
]
}

</script>
<template>
    <el-card>
        <el-form label-width="100px" :model="formData" :rules="formRules">
            <el-form-item label="sku名称" prop="skuName">
                <el-input v-model="formData.skuName" placeholder="请输入sku名称"></el-input>
            </el-form-item>
            <el-form-item label="价格（元）" prop="price">
                <el-input v-model="formData.price" type="number" placeholder="请输入价格"></el-input>
            </el-form-item>
            <el-form-item label="重量（克）" prop="weight">
                <el-input v-model="formData.weight" type="number" placeholder="请输入重量）"></el-input>
            </el-form-item>
            <el-form-item label="sku描述" prop="skuDesc">
                <el-input v-model="formData.skuDesc" type="textarea" placeholder="请输入sku描述" ></el-input>
            </el-form-item>
            <el-form-item label="平台属性">
                <el-form :model="formData" inline label-width="80px" class="line-form" :rules="attributeFormRules">
                    <el-form-item prop="valueId" v-for="(item,index) in attributeList" :key="item.id" :label="item.attrName">
                        <el-select v-model="formData.skuAttrValueList[index].valueId">
                            <el-option v-for="i in item.attrValueList" :key="i.id" :label="i.valueName" :value="i.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-form inline :rules="saleAttrFormRules" :model="formData">
                    <el-form-item prop="saleAttrValueId" v-for="(item,index) in saleAttrList" :key="item.id" :label="item.saleAttrName">
                        <el-select v-model="formData.skuSaleAttrValueList[index].saleAttrValueId"  style="width: 200px;"> 
                            <el-option v-for="i in item.spuSaleAttrValueList" :key="i.id" :label="i.saleAttrValueName" :value="i.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片名称">
                <el-table
                    style="width: 100%"
                    border
                    :data="formData.skuImageList"
                    ref="tableImgRef"
                >
                    <el-table-column header-align="center" align="center" type="selection" width="100" />
                    <el-table-column header-align="center" align="center" label="图片" width="240" >
                        <template v-slot="{ row }">
                            <div class="imgBox"  :style="{backgroundImage: `url(${row.imgUrl})`}
                            "></div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="imgName" header-align="center" align="center" label="名称" width="240" />property="name" label="名称" width="240" />
                    <el-table-column header-align="center" align="center"  label="操作" >
                        <template v-slot="{ row }">
                            <el-button v-if="row.isDefault" type="success">默认图片</el-button>
                            <el-button v-else type="warning" @click="handelDefaultImg(row)">设置默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button size="large" type="primary" @click="addSku">保存</el-button>
                <el-button size="large" @click="handleCancel">取消</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>
<style scoped lang="scss">
.line-form {
    .el-form-item {
        align-items: center;
        margin-bottom: 10px;
    }
    .el-select {
        width: 200px;

    }
}
.imgBox {
    width: 100%;
    height: 200px;
    background-size: cover;
    border-radius: 20px;
}
</style>